/*
给定一个链表，删除链表的倒数第 n 个节点，并且返回链表的头结点。

示例：

给定一个链表: 1->2->3->4->5, 和 n = 2.

当删除了倒数第二个节点后，链表变为 1->2->3->5.
说明：

给定的 n 保证是有效的。

来源：力扣（LeetCode）
链接：https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list
*/

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */


struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(nullptr) {}
};


#include <iostream>
using namespace std;

class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n);
};

ListNode* Solution::removeNthFromEnd(ListNode* head, int n)
{
    ListNode *leftHead = head;
    ListNode *leftNode = head;
    ListNode *rightNode = head;

    auto count = 0;
    for (;rightNode != nullptr; rightNode = rightNode->next)
    {
        if (n == count)
        {
            leftHead = leftNode;
            leftNode = leftNode->next;
        }
        else
        { 
            ++count;
        }
    }

    if (leftHead == head 
        and leftHead == rightNode)
    {
        return nullptr;
    }

    if (leftHead == leftNode)
    {
        return leftNode->next;
    }

    leftHead->next = leftNode->next;
    return head;
}


int main()
{
    ListNode *head = nullptr;
    ListNode *curr = nullptr;
    for (auto i=1; i<=1; ++i)
    {
        if (nullptr == head)
        {
            head = new ListNode(i);
            curr = head;
        }
        else
        {
            ListNode *tmp = new ListNode(i);
            curr->next = tmp;
            curr = tmp;
        }
    }

    for (auto iter=head; iter != nullptr; iter = iter->next)
    {
        cout << iter->val << "   ";
    }
    cout << endl;

    Solution obj;
    ListNode *ret = obj.removeNthFromEnd(head, 1);
    
    for (auto iter=ret; iter != nullptr; iter = iter->next)
    {
        cout << iter->val << "  ";
    }
    cout << endl;
}